package com.ccys.cms.controller.inventory;


import cn.hutool.core.util.IdUtil;
import com.ccys.cms.service.inventory.InventoryFeedService;
import com.ccys.cms.service.inventory.StaffPurchaseDetailService;
import com.ccys.cms.service.inventory.StaffPurchaseService;
import com.ccys.cms.service.productAndService.ProductService;
import com.ccys.common.util.HtmlUtils;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.web.inventory.StaffPurchaseDto;
import com.ccys.db.dto.web.inventory.StaffPurchasePageDto;
import com.ccys.db.dto.web.productAndService.NumEnum;
import com.ccys.db.entity.*;
import com.ccys.db.mapper.TblStaffPurchaseMapper;
import com.ccys.db.vo.web.inventory.*;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/inventory")
@Api(tags = "员工采购")
public class StaffPurchaseController {

    @Resource
    private StaffPurchaseService service;

    @Resource
    private StaffPurchaseDetailService detailService;

    @Resource
    private ProductService productService;

    @Resource
    private InventoryFeedService feedService;

    @Resource
    private TblStaffPurchaseMapper staffPurchaseMapper;

    @ApiOperation("新增")
    @PostMapping("staffPurchase")
    @Transactional
    public ResponseResult save(@RequestBody StaffPurchaseDto dto) {

        long createdOnUtc = new Date().getTime();
        TblStaffPurchase order = dto.getOrder();
        List<TblStaffPurchaseDetail> detailList = dto.getDetailList();
        //生成code
        String code = IdUtil.getSnowflakeNextId() + "";
        order.setCode(code);
        int num = service.insertOrUpdate(order);
        //生成detail编号
        //生成规则:根据顺序，在采购单的 code 后面添加 3 为数字，例如:xxxxx001,xxxxx002
        for (int i = 0; i < detailList.size(); i++) {
            String formattedNumber = String.format("%03d", i);
            String detailCode = code + formattedNumber;
            TblStaffPurchaseDetail detail = detailList.get(i);
            detail.setCode(detailCode);
            detail.setStaffPurchaseId(order.getId());
            detail.setId(IdUtil.getSnowflakeNextIdStr());
            detail.setCreatedOnUtc(createdOnUtc);
        }
        detailService.insertAll(detailList);
        //修改产品库存
        List<TblProduct> productList = new ArrayList<>();
        List<TblInventoryFeed> feedList = new ArrayList<>();
        for (int j = 0; j < detailList.size(); j++) {
            TblStaffPurchaseDetail detail = detailList.get(j);
            String productId = detail.getProductId();
            Integer quantity = detail.getQuantity();
            TblProduct product = new TblProduct();
            product.setId(productId);
            product.setQtyImportInStock(quantity);
            productList.add(product);
            TblInventoryFeed feed = new TblInventoryFeed();
            feed.setProductId(productId);
            feed.setQuantity(quantity);
            BigDecimal priceUnit = detail.getSellingPriceUnit();
            feed.setCostPricePerUnit(priceUnit);
            //null 进货 2 -> paid,4 -> manual adjustment, 5 -> write_off(废弃) ,6 -> staff purchase,7 -> 退换货中的退货(2.0新增)
            feed.setType(6);
            feed.setPurchaseOrderId(detail.getStaffPurchaseId());
            feed.setPurchaseOrderDetailId(detail.getId());
            feed.setId(IdUtil.getSnowflakeNextIdStr());
            feed.setCreatedOnUtc(createdOnUtc);
            feedList.add(feed);

        }

        if (CollectionUtils.isNotEmpty(productList)) {
            productService.updateBatchImportQuantity(productList);
        }
        //添加库存流水
        feedService.insertAll(feedList);
        return ResponseResult.update(num);
    }


    @ApiOperation("根据id查询")
    @GetMapping("staffPurchase/detail")
    public ResponseResult<GetStaffPurchaseDetailVo, Object> getById(String id) {
        GetStaffPurchaseDetailVo vo = staffPurchaseMapper.getStaffPurchaseDetailById(id);
        return ResponseResult.success(vo);
    }

    @ApiOperation("根据id删除")
    @DeleteMapping("staffPurchase")
    @Transactional
    public ResponseResult delete(String id) {

        TblStaffPurchase model = new TblStaffPurchase();
        model.setId(id);
        model.setDelFlag(NumEnum.DEL.getCode());
        int i = service.updateEntityById(model);
        //删除deltail
        detailService.deleteDetail(id);
        return ResponseResult.update(i);
    }


    @ApiOperation(value = "查询分页", notes = "排序字段 t1.code (指的是purchaseNo列) / t4.first_name / t1.total_amount /  t1.purchase_date /t2. user_fullname / t1.created_on")
    @GetMapping("staffPurchase")
    public ResponseResult<PageInfo<StaffPurchaseVo>, Object> getPage(StaffPurchasePageDto dto) {
        return service.getPage(dto);
    }


    @ApiOperation(value = "下载pdf")
    @GetMapping("downloadPDF/staffPurchase")
    public ResponseResult download(String id, HttpServletResponse response) throws Exception {
        BigDecimal zero = new BigDecimal(0);
        StaffPurchasePDFVo data = staffPurchaseMapper.getStaffPurchasePDFData(id);
        //计算GST
        double gst = Optional.ofNullable(data.getTax()).orElse(zero)
                .multiply(Optional.ofNullable(data.getSubtotalExcludingGST()).orElse(zero))
                //百分数除以100
                .divide(new BigDecimal(100))
                .doubleValue();
        data.setGST(new BigDecimal(gst));
        HashMap<String, Object> mapData = Maps.newHashMap();
        mapData.put("data", data);
        long timeMillis = System.currentTimeMillis();
        String templateContent = HtmlUtils.getTemplateContent("Staff_Purchase_Receipt.ftl", mapData);
        HtmlUtils.html2Pdf(response, templateContent, timeMillis + "");
        return ResponseResult.success();
    }



}
